# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order import db as order_db
from common.channel.pay import check_channel_order
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '79': {  # WITCH 时空支付 100-10000 支付宝跳转淘宝 3%
        'API_KEY': '4490ec5d565dadf5f3fea235797246f5',
        'gateway': 'https://www.ji152.cn/pay',
        'query_gateway': 'https://www.ji152.cn/api/getStatusByOrderId',
    },
    '80': {  # LOKI 时空支付 100-10000 支付宝跳转淘宝 3%
        'API_KEY': 'f0aa3b42353a9cef94ca32b7a46b883e',
        'gateway': 'https://www.ji152.cn/pay',
        'query_gateway': 'https://www.ji152.cn/api/getStatusByOrderId',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def generate_sign(parameter, key):
    s = parameter['goodsname'] + '+' + str(parameter['istype']) + '+' + parameter['notify_url'] \
        + '+' + parameter['orderid'] + '+' + parameter['orderuid'] + '+' + str(parameter['price']) + '+' \
        + parameter['return_url'] + '+' + key + '+' + parameter['uid']
    return _gen_sign(s)


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def query_sign(params, key):
    s = params['uid'] + '+' + params['orderid'] + '+' + params['r'] + '+' + key
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['key']
    s = params['orderid'] + '+' + params['orderuid'] + '+' + params['platform_trade_no'] + '+' \
        + params['price'] + '+' + params['realprice'] + '+' + key
    calculated_sign = _gen_sign(s)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("shikongpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


# 付款方式编号
# 1 支付宝 2 微信
def _get_pay_type(service):
    if service == 'alipay':
        return '1'
    elif service == 'wxpay':
        return '2'
    return '1'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('price', '%.2f' % pay_amount),
        ('istype', int(_get_pay_type(service))),
        ('notify_url',
         '{}/pay/api/{}/shikongpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('return_url',
         '{}/pay/api/{}/shikongpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('orderid', str(pay.id)),
        ('orderuid', 'charge'),
        ('goodsname', 'charge'),
        ('attach', 'web'),
    ))
    parameter_dict['key'] = generate_sign(parameter_dict, api_key)
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info("shikongpay create charge data: %s, order_id is: %s ", json.dumps(parameter_dict),
                 parameter_dict['orderid'])
    return {'charge_info': url}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("shikongpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['orderid']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('shikongpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = 'success'
    trade_no = data['platform_trade_no']
    total_fee = float(data['realprice'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'success':
        _LOGGER.info('shikongpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('uid', app_id),
        ('orderid', str(pay_order.id)),
        ('r', str(int(time.time()))),
    ))
    parameter_dict['key'] = query_sign(parameter_dict, api_key)
    _LOGGER.info("shikongpay query data: %s, order_id is: %s ", parameter_dict, parameter_dict['orderid'])
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=3, verify=False)
    _LOGGER.info("shikongpay query  rsp data: %s,%s", response.text, response.url)
    if response.status_code == 200:
        data = json.loads(response.text)['data']
        mch_id = pay_order.mch_id
        trade_status = str(data['status'])
        total_fee = float(data['realprice'])
        trade_no = data['orderid']

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 0-等待支付；1-付款成功；2-已关闭
        if trade_status == '1':
            _LOGGER.info('shikongpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
